from __future__ import print_function
from copy import copy

from util import tuplifyTree

def uppercase(lex, dyn, s):
  return s.upper()

def lowercase(lex, dyn, s):
  return s.lower()

def read(lex, dyn, channel):
  method=channel['get']
  return ({}, {}, ['func', [method, []]])

def receive(lex, dyn, inputChannel, f):
  return ({}, {}, ['func', [f, [({}, {}, ['literal', inputChannel])]]])

def send(lex, dyn, value, channel):
  return ['literal', ['message', ['literal', value], ['literal', channel]]]

def mutate(lex, dyn, value, name):
  return ['literal', ['mutation', value, name]]

def arbre_print(lex, dyn, s):
  from termcolor import colored
  if type(s)==str:
    print(colored(s, 'green'), end='')
  else:
    print(colored(s, 'green'))
  return None

def arbre_return(lex, dyn, value):
  return value

def append(lex, dyn, a, b):
  return a+b

def add(lex, dyn, a, b):
  return a+b

def subtract(lex, dyn, a, b):
  return a-b

def multiply(lex, dyn, a, b):
  return a*b

def divide(lex, dyn, a, b):
  return a / b

def arbre_and(lex, dyn, a, b):
  return a and b

def arbre_or(lex, dyn, a, b):
  return a or b

def arbre_not(lex, dyn, a):
  return not a

def lt(lex, dyn, a, b):
  return a<b

def gt(lex, dyn, a, b):
  return a>b

def eq(lex, dyn, a, b):
  return a==b

def arbre_eval(lex, dyn, block, args):
  params=block['params']
  code=block['code']

  dyn=copy(dyn)
  for x in range(len(params)):
    dyn[params[x]]=args[x]
  return tuplifyTree(lex, dyn, code)

def arbre_with(lex, dyn, var, value, block):
  dyn=copy(dyn)
  dyn[var]=tuplifyTree(lex, dyn, ['literal', value])
  code=tuplifyTree(lex, dyn, ['block', block])
  args=tuplifyTree(lex, dyn, ['literal', []])
  return (lex, dyn, ['func', ['eval', [code, args]]])

def arbre_if(lex, dyn, condition, ifBlock, elseBlock):
  if condition:
    code=tuplifyTree(lex, dyn, ['block', ifBlock])
  else:
    code=tuplifyTree(lex, dyn, ['block', elseBlock])

  args=tuplifyTree(lex, dyn, ['literal', []])

  return (lex, dyn, ['func', ['eval', [code, args]]])
